package com.banmajio.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/threadpool")
public class ThreadPoolAdminController {

    private final Logger log = LoggerFactory.getLogger(ThreadPoolAdminController.class);
    private final ThreadPoolTaskExecutor dataMigrationExecutor;

    @Autowired
    public ThreadPoolAdminController(ThreadPoolTaskExecutor dataMigrationExecutor) {
        this.dataMigrationExecutor = dataMigrationExecutor;
    }

    /**
     * 强制关闭数据迁移线程池
     */
    @PostMapping("/shutdown")
    public ResponseEntity<String> forceShutdown() {
        try {
            log.info("收到强制关闭线程池请求");
            
            // 获取原生线程池
            ThreadPoolExecutor threadPool = dataMigrationExecutor.getThreadPoolExecutor();
            
            // 检查线程池状态
            if (threadPool.isShutdown() || threadPool.isTerminated()) {
                return ResponseEntity.ok("线程池已关闭或已终止");
            }
            
            // 记录当前线程池状态
            log.info("关闭前线程池状态: 活跃线程数={}, 队列大小={}, 已完成任务数={}, 总任务数={}",
                    threadPool.getActiveCount(),
                    threadPool.getQueue().size(),
                    threadPool.getCompletedTaskCount(),
                    threadPool.getTaskCount());
            
            // 尝试优雅关闭
            dataMigrationExecutor.shutdown();
            
            // 等待30秒
            if (!threadPool.awaitTermination(30, TimeUnit.SECONDS)) {
                // 强制关闭
                List<Runnable> remainingTasks = threadPool.shutdownNow();
                log.info("强制关闭线程池，已取消 {} 个未执行的任务", remainingTasks.size());
            }
            
            log.info("线程池已成功关闭");
            return ResponseEntity.ok("线程池已成功关闭");
            
        } catch (Exception e) {
            log.error("关闭线程池时出错", e);
            return ResponseEntity.status(500).body("关闭线程池失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取线程池状态
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getStatus() {
        ThreadPoolExecutor threadPool = dataMigrationExecutor.getThreadPoolExecutor();
        
        Map<String, Object> status = new HashMap<>();
        status.put("isShutdown", threadPool.isShutdown());
        status.put("isTerminated", threadPool.isTerminated());
        status.put("activeThreads", threadPool.getActiveCount());
        status.put("queueSize", threadPool.getQueue().size());
        status.put("completedTasks", threadPool.getCompletedTaskCount());
        status.put("totalTasks", threadPool.getTaskCount());
        
        return ResponseEntity.ok(status);
    }
}